'''
都会二号疾病保险产品组合-10年缴
'''

import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json,time
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "都会二号疾病保险产品组合-10年缴"
    # 生成产品数据
    def genProductInfo(self):
        #年龄 1 - 55
        plan = {

            "planA":{
                #年龄段
                "year":[str(i) for i in range(1,56)],
                # 性别 M 男 F 女
                "gender":["M","F"],
                #保险金额
                "money":["100000"],
                #保障期限 /年
                "expire":["终身"],
                #缴费期限
                "paytime":["10"],
                #缴费间隔 1 月缴 12 年缴
                "interval":["1","12"],
                #投保对象
                "payObject":["本人/配偶/子女/父母"]
            },
            "planB":{

                # 年龄段
                "year": [str(i) for i in range(1, 56)],
                # 性别 M 男 F 女
                "gender": ["M", "F"],
                # 保险金额
                "money": ["150000"],
                # 保障期限 /年
                "expire": ["终身"],
                # 缴费期限
                "paytime": ["10"],
                # 缴费间隔 1 月缴 12 年缴
                "interval": ["1", "12"],
                # 投保对象
                "payObject": ["本人/配偶/子女/父母"]

            },
            "planC":{

                # 年龄段
                "year": [str(i) for i in range(1, 56)],
                # 性别 M 男 F 女
                "gender": ["M", "F"],
                # 保险金额
                "money": ["300000"],
                # 保障期限 /年
                "expire": ["终身"],
                # 缴费期限
                "paytime": ["10"],
                # 缴费间隔 1 月缴 12 年缴
                "interval": ["1", "12"],
                # 投保对象
                "payObject": ["本人/配偶/子女/父母"]
            },
            "planD":{

                # 年龄段
                "year": [str(i) for i in range(1, 56)],
                # 性别 M 男 F 女
                "gender": ["M", "F"],
                # 保险金额
                "money": ["500000"],
                # 保障期限 /年
                "expire": ["终身"],
                # 缴费期限
                "paytime": ["10"],
                # 缴费间隔 1 月缴 12 年缴
                "interval": ["1", "12"],
                # 投保对象
                "payObject": ["本人/配偶/子女/父母"]

            }

        }
        for k in plan:

            for v in product( plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["expire"],plan[k]["paytime"],plan[k]["interval"],plan[k]["payObject"]):

                #写入数据库
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( v[0],v[1],v[2],v[3],v[4],v[5],v[6]))
                self.mysql._conn.commit()
                print("%s产品信息保持成功"%self.name )


    #执行爬虫
    def requestJson(self,dt=None):

        data = {

            "appName":"",
            "appSex":dt["gender"],
            "appidType":"A",
            "appidNo":"",
            "appBirthday":"{year}-03-07".format( year = str( 2019-int(dt["year"]))),
            "appPhone":"",
            "appPro": "110000",
            "appCity": "110100",
            "appAddress":"",
            "appEmail":"",
            "name":"",
            "sex": "M",
            "idType": "A",
            "idNo": "",
            "birthday": "{year}-03-07".format( year = str( 2019-int(dt["year"]))),
            "phone":"",
            "pro": "110000",
            "city": "110100",
            "address":"",
            "email":"",
            "source": "CUS000000046",
            "planCode": "P000000912",
            "planAmnt": dt["money"],
            "polTerm": "106",
            "poltermType": "A",
            "payPeriod": dt["paytime"],
            "payIntv": dt["interval"],
            "relation": "0",
            "validate":"",
        }

        data = ( urlencode(data).replace('+',''))

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=data)

        if r.status_code == 200 and r.json()["success"]:

            price = Helper.decimalParse( r.json()["msg"])

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }

            self.mysql.updateTask(data)

            self.requestJson(dt)

if __name__ == '__main__':

    s = Spider()
    s.genProductInfo()
    print("开始进行数据爬取..")
    s.main()

